#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

from bs4 import BeautifulSoup
import multiprocessing
import os
import sys

default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)


def ParsePMCArticle(article_string):
    soup = BeautifulSoup(article_string, "html.parser")
    pmcid = soup.find("article-id", attrs={"pub-id-type": "pmc"}).string
    manuscript = soup.find("article-id", attrs={"pub-id-type": "manuscript"})
    is_manuscript = False
    if manuscript != None:
        is_manuscript = True
    return (pmcid + "\t" + str(is_manuscript))


def FindInfo(filename):
    infile = open(filename, "r")
    outfile = open(filename + ".content", "w")
    current_string = ""
    for line in infile:
        line = line.rstrip()
        current_string += line
        if line.find("</article>") != -1:
            result = ParsePMCArticle(current_string)
            outfile.write(result + "\n")
            outfile.flush()
            current_string = ""
    infile.close()
    outfile.close()
    print(filename + " complete.")


if __name__ == "__main__":
    # pool = multiprocessing.Pool(processes=10)
    #
    # list = os.listdir(".")
    # for filename in list:
    #     if filename.endswith(".xml"):
    #         pool.apply_async(FindInfo, (filename,))
    # pool.close()
    # pool.join()
    FindInfo(sys.argv[1])
    # for i in xrange(1, 368):
    #     FindInfo("pmc_id_" + str(i) + ".xml")
